#include "buildCamera.h"
#include "buildFilm.h"

#include <cameras/perspective.h>
#include <cameras/orthographic.h>
#include <core/transform.h>

#include <RenderOutputUtils/RenderOutputUtils.h>

Camera *getCamera( FnKat::Render::RenderSettings &renderSettings,
                   FnKat::FnScenegraphIterator rootIt,
                   BasicSettings* basicSettings)
{
    ParamSet p;

    // Get Camera location and info
    string cameraLocation = renderSettings.getCameraName();
    FnKat::RenderOutputUtils::CameraInfo cameraInfo =
            FnKat::RenderOutputUtils::getCameraInfo(rootIt, cameraLocation);

    // Is it Ortho?
    bool ortho = (bool)cameraInfo.getOrtho();

    // Get the Film
    Film *film = getFilm(renderSettings, "primary", basicSettings);
    if (film == NULL)
    {
        return NULL;
    }

    //Convert cameraInfo.getXForm() to Transform
    //TODO: make sure it is deallocated
    //TODO: check why need 2 xforms
    float mat[4][4];
    for(int j = 0; j < 4; ++j)
    {
        for(int i = 0; i < 4; ++i)
        {
            mat[j][i] = (float)cameraInfo.getXForm()[i * 4 + j];
        }
    }

    //TODO: clean
    Transform mXform(mat);
    mXform = mXform * Scale(1, 1, -1);

    Transform *xform = new Transform(mXform);

    // TODO: get real animated values
    AnimatedTransform animXform(xform, 0.0f, xform, 1.0f);

    // Create and return the camera
    if(ortho)
    {
        return CreateOrthographicCamera(p, animXform, film);
    }
    else
    {
        // FOV
        float fov = cameraInfo.getFov();
        p.AddFloat("fov", &fov, 1);

        return CreatePerspectiveCamera(p, animXform, film);
    }

    return NULL;
}
